<template>
  <el-tabs type="border-card" class="order-container">
    <el-tab-pane label="活动管理">
      <!-- 头部 -->
      <el-input v-model="marketList.id" style="width: 20%; margin-right: 20px; margin-bottom: 20px"
        placeholder="活动ID"></el-input>
      <el-select v-model="marketList.type" clearable placeholder="活动类型"
        style="width: 20%; margin-right: 20px; margin-bottom: 20px">
        <el-option v-for="item in marketType" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-select v-model="marketList.status" clearable placeholder="活动状态"
        style="width: 20%; margin-right: 20px; margin-bottom: 20px">
        <el-option v-for="item in marketStatus" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="conditionGetMarketList">查询</el-button>
      <el-button type="primary" icon="el-icon-brush" @click="clearCondition"></el-button>
      <el-button type="primary" icon="el-icon-plus" @click="addMarket">活动</el-button>
      <!-- /头部 -->
      <!-- 表格 -->
      <el-table :data="tableData" style="width: 100%" :header-cell-style="{ background: '#EDF4FF', color: '#606266' }">
        <el-table-column label="活动图片" width="150">
          <template slot-scope="{ row }">
            <el-row>
              <el-image style="width: 60px; height: 60px" :src="row.bannerImage"></el-image>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="活动名称" width="150">
        </el-table-column>
        <el-table-column prop="type" label="活动类型" width="150">
          <template slot-scope="{ row }">
            <el-tag v-if="row.type === 1">新品推荐</el-tag>
            <el-tag v-if="row.type === 2">限时特惠</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="beginTime" label="开始时间" width="150">
          <template slot-scope="{ row }">
            <i class="el-icon-timer"></i>
            <span style="margin-left: 10px">{{ row.beginTime }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="overTime" label="结束时间" width="150">
          <template slot-scope="{ row }">
            <i class="el-icon-timer"></i>
            <span style="margin-left: 10px">{{ row.overTime }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="150">
          <template slot-scope="{ row }">
            <el-switch v-model="row.status" :active-value="1" :inactive-value="2" @change="statusChange(row.id, $event)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button size="small" @click="editMarket(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deletMarket(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- /表格 -->
      <!-- 分页 -->
      <el-row type="flex">
        <el-pagination background layout="total,prev, pager, next" :total="total" :page-size="marketList.pageSize"
          :current-page="marketList.pageNum" @current-change="changePage">
        </el-pagination>
      </el-row>
      <!-- /分页 -->
      <!-- 弹层 -->
      <el-dialog :title="title" :visible.sync="dialogVisible" width="50%" :before-close="handleClose">
        <el-form :model="marketForm" :rules="rules" label-width="100px" ref="setMarketForm">
          <el-form-item label="活动名称" prop="name">
            <el-input v-model="marketForm.name" style="width: 80%" placeholder="请输入名称" maxlength="20"
              show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="活动类型" prop="type">
            <el-select v-model="marketForm.type" clearable placeholder="请选择"
              style="width: 50%; margin-right: 20px; margin-bottom: 20px">
              <el-option v-for="item in marketType" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="活动图片" prop="bannerImage">
            <el-upload class="avatar-uploader" :show-file-list="false" action="http://124.222.107.144:4020/web/upload"
              :headers="headers" list-type="picture-card" :before-remove="beforeRemove" :on-success="successfn"
              :on-error="errorfn" :on-exceed="handleExceed">
              <img v-if="marketForm.bannerImage" :src="marketForm.bannerImage" class="avatar"
                style="width: 100%; height: 100%" />
              <i v-else class="el-icon-plus"></i>
              <!-- <div slot="file" slot-scope="{ file }">
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="marketForm.bannerImage"
                  alt=""
                />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div> -->
            </el-upload>
            <el-dialog :visible.sync="picturVisible">
              <img width="100%" :src="marketForm.bannerImage" alt="" />
            </el-dialog>
          </el-form-item>
          <el-form-item label="开始时间" prop="beginTime">
            <el-date-picker v-model="marketForm.beginTime" type="datetime" placeholder="请选择开始时间" align="right"
              :picker-options="pickerOptions" value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间" prop="overTime">
            <el-date-picker v-model="marketForm.overTime" type="datetime" placeholder="请选择结束时间" align="right"
              :picker-options="pickerOptions" value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="关联商品" prop="goodsIds">
            <el-table :data="goods" style="width: 100%" empty-text="你还没有添加活动商品哦"
              :header-cell-style="{ background: '#EDF4FF', color: '#606266' }">
              <el-table-column label="主图" width="106">
                <template slot-scope="{ row }">
                  <el-image style="width: 60px; height: 60px" :src="row.imageUrl"></el-image>
                </template>
              </el-table-column>
              <el-table-column prop="title" label="标题" width="106">
              </el-table-column>
              <el-table-column prop="price" label="价格" width="106">
              </el-table-column>
              <el-table-column width="106">
                <template slot="header">
                  <!-- 关联商品添加 -->
                  <el-popover placement="left" width="400" trigger="manual" v-model="visiblepop">
                    <el-table :data="beforeGoodDatas" height="400" tooltip-effect="dark" :row-key="
                      (row) => {
                        return row.id;
                      }
                    " @selection-change="selectionLineChangeHandle" ref="beforeTable">
                      <el-table-column type="selection" width="55" :reserve-selection="true">
                      </el-table-column>
                      <el-table-column width="120" property="date" label="主图">
                        <template slot-scope="{ row }">
                          <el-image style="width: 60px; height: 60px" :src="row.imageUrl"></el-image>
                        </template>
                      </el-table-column>
                      <el-table-column width="100" property="title" label="标题"></el-table-column>
                      <el-table-column width="100" property="price" label="价格"></el-table-column>
                    </el-table>
                    <el-button slot="reference" type="primary" @click="searchMarketGoods"
                      class="el-icon-plus"></el-button>

                    <div style="margin-top: 10px; text-align: right">
                      <el-button @click="popoverCancel">取 消</el-button>
                      <el-button type="primary" @click="fromCommit">确 定</el-button>
                    </div>
                  </el-popover>
                </template>
                <template slot-scope="{ row }">
                  <el-button type="danger" class="el-icon-minus" @click="remove(row.id)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="btnCancel('cancel')">取 消</el-button>
          <el-button @click="btnCancel('reset')">重置</el-button>
          <el-button type="primary" @click="isOk">确 定</el-button>
        </span>
      </el-dialog>
      <!-- /弹层 -->
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import {
  getMarketList,
  updataMarketStatus,
  deletMarket,
  searchMarketGoods,
  createMarket,
  updataMarket,
} from "@/api/actives";
import store from "@/store";
export default {
  name: "",
  components: {},
  data() {
    return {
      // 选择查询类型
      marketType: [
        {
          value: 1,
          label: "新品推荐",
        },
        {
          value: 2,
          label: "限时特惠",
        },
      ],
      // 选择查询状态
      marketStatus: [
        {
          value: "1",
          label: "进行中",
        },
        {
          value: "2",
          label: "已结束",
        },
      ],
      //表格数据
      tableData: [],
      total: 0,
      //发送请求活动列表
      marketList: {
        id: "",
        type: "",
        status: "",
        pageNum: 1,
        pageSize: 5,
        sid: store.getters.sid,
      },
      rules: {
        name: [
          { required: true, message: "活动名称不能为空", trigger: "blur" },
        ],
        type: [{ required: true, message: "请选择活动类型", trigger: "blur" }],
        bannerImage: [
          { required: true, message: "请添加活动图片", trigger: "blur" },
        ],
        beginTime: [
          { required: true, message: "请选择开始时间", trigger: "blur" },
        ],
        overTime: [
          { required: true, message: "请选择结束时间", trigger: "blur" },
        ],
        goodsIds: [
          { required: true, message: "请选择关联商品", trigger: "blur" },
        ],
      },
      //弹层的显示与关闭
      dialogVisible: false,
      //弹层标题
      title: "",
      selectOption: "",
      //弹层表单数据
      marketForm: {
        name: "",
        type: "",
        bannerImage: "",
        beginTime: "",
        overTime: "",
        goodsIds: "",
        sid: Number(store.getters.sid),
      },
      // 编辑时，发送的数据
      editData: {
        id: "",
        name: "",
        type: "",
        bannerImage: "",
        beginTime: "",
        overTime: "",
        goodsIds: "",
        status: "",
      },
      // 弹层里关联商品数据
      goods: [],
      beforeGoodDatas: [],
      picturVisible: false,
      disabled: false,
      // el-popover的显示
      visiblepop: false,
      // 选择关联商品数据
      dataonLineListSelections: [],
      //  图片上传请求头
      headers: {
        token: store.getters.token,
      },
      //选择时间的快捷方式
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
    };
  },
  computed: {},
  created() {
    this.getMarketList();
  },
  methods: {
    //查询活动列表
    async getMarketList() {
      const { total, list } = await getMarketList(this.marketList);
      this.total = total;
      this.tableData = list;
      console.log(list);
    },
    // 根据条件查询
    conditionGetMarketList() {
      this.marketList.pageNum = 1;
      this.getMarketList();
    },
    // 清除刷新
    clearCondition() {
      this.marketList.id = "";
      this.marketList.type = "";
      this.marketList.status = "";
      this.marketList.pageNum = 1;
      // 重新拉取数据
      this.getMarketList();
    },
    // 添加活动
    addMarket() {
      this.title = "添加活动";
      this.selectOption = "add";
      this.dialogVisible = true;
    },
    //编辑活动
    async editMarket(row) {
      this.title = "编辑活动";
      this.selectOption = "edit";
      this.dialogVisible = true;

      this.marketForm = {
        name: row.name,
        type: row.type,
        bannerImage: row.bannerImage,
        // bannerImage: 'https://img1.baidu.com/it/u=3494536116,3351731546&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        beginTime: row.beginTime,
        overTime: row.overTime,
        goodsIds: row.goodsIds,
        sid: Number(store.getters.sid),
        id: row.id,
        status: row.status,
      };
      // 单独保存关联商品的goodsIds
      // this.selectionKeys=row.goodsIds
      //点击编辑时，同时根据goodsIds查询出关联的商品
      const res = await searchMarketGoods(row.goodsIds);
      this.goods = res;
    },
    async isOk() {
      try {
        this.$refs.setMarketForm.validate(async (ok) => {
          if (ok) {
            if (this.selectOption === "add") {
              console.log("添加请求参数", this.marketForm);
              await createMarket(this.marketForm);
              this.$message.success("添加成功");
            }
            if (this.selectOption === "edit") {
              //当选择取消的关联商品时，marketForm.goodsIds应该要更新
              // 所有在点击确定编辑时，更新
              let ids = "";
              for (var i = 0; i < this.goods.length; i++) {
                ids = ids + this.goods[i].id;
                if (i + 1 < this.goods.length) {
                  ids = ids + ",";
                }
              }
              // 给goodsIds赋值
              this.marketForm.goodsIds = ids;
              //
              this.editData = {
                ...this.marketForm,
              };
              console.log("编辑数据", this.editData);
              await updataMarket(this.editData);
              this.$message.success("编辑成功");
            }
            this.dialogVisible = false;
            this.getMarketList(); //重新拉取数据
            this.selectOption = "";
            this.marketForm = {
              name: "",
              type: "",
              bannerImage: "",
              beginTime: "",
              overTime: "",
              goodsIds: "",
              sid: Number(store.getters.sid),
            };
            this.goods = [];
          }
        });
      } catch (error) {
        console.log(error);
      }
    },
    // 弹层的取消
    btnCancel(option) {
      this.marketForm = {
        name: "",
        type: "",
        bannerImage: "",
        beginTime: "",
        overTime: "",
        goodsIds: "",
        sid: Number(store.getters.sid),
      };
      this.$refs.setMarketForm.resetFields();
      if (option === "cancel") {
        this.dialogVisible = false;
      }
      // if (option === "reset") {
      this.goods = [];
      // }
    },
    // 查询营销活动商品
    async searchMarketGoods() {
      const res = await searchMarketGoods();
      console.log("营销活动商品", res);
      this.beforeGoodDatas = res;
      // 打开的时候修改状态
      this.visiblepop = !this.visiblepop;
      // 回显已经勾选的关联商品
      // const selectionKeys = this.marketForm.goodsIds;
      // const { selectionKeys, beforeGoodDatas } = this
      this.goods.forEach((item) => {
        this.beforeGoodDatas.forEach((row) => {
          if (row.id == item.id) {
            this.$refs.beforeTable.toggleRowSelection(row, true);
          }
        });
      });
    },
    // 选择的营销活动
    selectionLineChangeHandle(val) {
      this.dataonLineListSelections = val;
    },
    // 提交营销活动
    fromCommit() {
      console.log(this.dataonLineListSelections);
      var ids = "";
      for (var i = 0; i < this.dataonLineListSelections.length; i++) {
        // console.log("id:" + this.dataonLineListSelections[i].id);
        ids = ids + this.dataonLineListSelections[i].id;
        if (i + 1 < this.dataonLineListSelections.length) {
          ids = ids + ",";
        }
      }
      this.goods = this.dataonLineListSelections;
      // 给goodsIds赋值
      this.marketForm.goodsIds = ids;
      // 点击确认后el-popover弹层消失
      this.visiblepop = false;
      // 清除勾选的
      this.$refs.beforeTable.clearSelection();
    },
    // 点击取消el-popover
    popoverCancel() {
      this.visiblepop = false;
      // 同时查看goods里面是否有数据，没有数据则证明没有提交，取消时应该清空选项
      // if (this.goods.length === 0) {
      this.$refs.beforeTable.clearSelection();
      // }
    },
    // 取消选择的关联商品
    remove(optionid) {
      this.goods = this.goods.filter((item) => {
        return item.id != optionid;
      });
    },
    // 弹层图片方法
    handleRemove(file) {
      console.log(file);
      this.marketForm.bannerImage = "";
    },
    handlePictureCardPreview(file) {
      this.marketForm.bannerImage = file.url;
      this.picturVisible = true;
    },
    // 点击删除前触发
    beforeRemove(file) {
      console.log("hhhhahhh");
      let flag = this.$confirm(`确定移除${file.name}`);
      console.log(flag);
      //   return flag;
    },
    // 上传成功时触发
    successfn(response, file, fileList) {
      //   console.log("哈哈哈哈，已经上传成功了");
      //   console.log(response, "=====", file, "=====", fileList);
      // this.marketForm.bannerImage = response.data;
      this.marketForm.bannerImage = 'https://img1.baidu.com/it/u=3494536116,3351731546&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500'
    },
    // 上传失败时触发
    errorfn(response, file, fileList) {
      console.log("啊哈，上传失败了？");
      console.log(response, "=====", file, "=====", fileList);
    },
    // 超出限制时触发
    handleExceed(file, fileList) {
      this.$message.warning(`超出限制了`);
    },
    //弹层关闭时的提示
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.btnCancel();
          done();
        })
        .catch((_) => { });
    },
    // 删除
    async deletMarket(id) {
      try {
        // 删除前提示
        await this.$confirm("确定要删除吗?删除后数据不可恢复！！！", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        // 删除
        await deletMarket(id);
        this.getMarketList(); //重新加载数据
        this.$message.success("删除角色成功");
      } catch (error) {
        console.log(error);
      }
    },
    // 改变状态时执行的回调函数
    async statusChange(id, status) {
      const data = {
        id: id,
        status: status,
      };
      console.log(data);
      const res = await updataMarketStatus(data);
      console.log(res);
    },
    // 分页
    changePage(newPage) {
      // newPage当前点击的页码
      // console.log(newPage);
      // 讲当前页码赋值给当前的最新页码
      this.marketList.pageNum = newPage;
      // 重新获取数据
      this.getMarketList();
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep #tab-0.is-active,
::v-deep #tab-1.is-active {
  background-color: #daeafd;
  border-radius: 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>